#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on 2016-11-28
 
@author: reggie

格式化代碼快捷鍵-Ctrl + Alt + L
'''
import os
import time
import platform
import xml.dom

# 指定Monkey日志文件的根目录
baseDirectory = 'E:\monkey\androidTestTools_monkey_python2\monkeyTest_20161206'


def getFile(basedir):
    filelists = []
    # 指定想要统计的文件类型
    whitelist0 = ['log']
    # 指定想要统计的文件名称
    whitelist1 = ['dropboxLog']
    # 遍历文件, 递归遍历文件夹中的所有
    # global filelists
    for parent, dirnames, filenames in os.walk(basedir):
        # for dirname in dirnames:
        # getFile(os.path.join(parent,dirname)) #递归
        for filename in filenames:
            # print filename
            ext0 = filename.split('.')[-1]
            ext1 = filename.split('.')[0]
            # 只统计指定的文件类型，略过一些log和cache文件
            if ext0 in whitelist0 and ext1 in whitelist1:
                filelists.append(os.path.join(parent, filename))
                # print(filename)#文件名
                # print(parent)#文件所在根目录
                # print(os.path.join(parent, filename))
    return filelists


def getVersionCode(packageName):
    if platform.system() == 'Windows':
        seek = 'findstr'
    else:
        seek = 'grep'
    tmp = os.popen('adb shell dumpsys package ' + packageName + ' | ' + seek + ' versionName').readline()
    versionCode = ""
    if tmp == "":
        versionCode = "v1.null"
        return versionCode
    else:
        versionCode = tmp.strip().split('=')[1].strip()
        return versionCode


def getLogsDetailed():
    # 全局
    global baseDirectory
    filelists = getFile(baseDirectory)
    # print filelists
    errorList = []
    for i in range(len(filelists)):
        fileDirectory = filelists[i]
        a = fileDirectory.strip().split('\\')
        b = a[-2].strip().split('_')
        packageName = b[-1]
        # print(packageName)
        versionCode = getVersionCode(packageName)
        # print(versionCode)
        # 读日志文件
        errorType = ''
        errorDetailed = ''
        fileObject = open(fileDirectory)
        try:
            # 报错详情
            errorDetailed = fileObject.read().strip()
            # 报错类型
            errorType = errorDetailed.split(':')[0]
            # print(errorType)
            # print(errorDetailed)
        finally:
            fileObject.close()
        data = {'packageName': packageName,
                'versionCode': versionCode,
                'errorType': errorType,
                'errorDetailed': errorDetailed}
        # print data
        errorList.append(data)
    print errorList
    # print errorList[0]
    return errorList


def createElement(doc, tag, attr):
    # 创建一个元素节点
    elementNode = doc.createElement(tag)
    # 创建一个文本节点
    textNode = doc.createTextNode(attr)
    # 将文本节点作为元素节点的子节点
    elementNode.appendChild(textNode)
    return elementNode


def createLogsXML():
    dom1 = xml.dom.getDOMImplementation()  # 创建文档对象，文档对象用于创建各种节点。
    doc = dom1.createDocument(None, "TestReport", None)
    top_element = doc.documentElement  # 得到根节点
    logs = getLogsDetailed()
    for log in logs:
        sNode = doc.createElement('BugDetailed')
        # sNode.setAttribute('id',str('0'))
        headNode = createElement(doc, 'packageName', log['packageName'])
        nameNode = createElement(doc, 'versionCode', log['versionCode'])
        numberNode = createElement(doc, 'errorType', log['errorType'])
        pageNode = createElement(doc, 'errorDetailed', log['errorDetailed'])
        sNode.appendChild(headNode)
        sNode.appendChild(nameNode)
        sNode.appendChild(pageNode)
        sNode.appendChild(numberNode)
        top_element.appendChild(sNode)  # 将遍历的节点添加到根节点下
    timestamp = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    xmlfile = open('MonkeyTestReport-' + timestamp + '.xml', 'w')
    doc.writexml(xmlfile, addindent=' ' * 4, newl='\n', encoding='utf-8')
    xmlfile.close()


if __name__ == '__main__':
    # getLogsDetailed()
    createLogsXML()
